require('webpack-jquery-ui');
var appContext = require('../../../config/app.context');

restaurantController.$inject = ['$scope', '$rootScope', '$location', '$stateParams', 'merchantService', 'dishService', 'cartService'];

function restaurantController($scope, $rootScope, $location, $stateParams, merchantService, dishService, cartService) {

    /** 
     * when accessing different merchant
     * notify user that cart will be cleared
     */
    var goBack = false;
    $rootScope.$on('loginedCustomer', function() {
        if (goBack) {
            return;
        }
        if ($rootScope.globalData.loginedCustomer && $location.path().indexOf('/restaurant/') != -1) {
            // console.log($location.path());
            var currentMerchantJson = window.sessionStorage.getItem('currentMerchant');
            $scope.cart = cartService.getCart($rootScope.globalData.loginedCustomer._id);

            // if (currentMerchantJson && JSON.parse(currentMerchantJson)._id != $stateParams.mId && $scope.cart.length > 0) {
            //     if (confirm('If you go into this restaurant, cart will be cleared.\nContinue?')) {
            //         cartService.setCart($rootScope.globalData.loginedCustomer._id, []);
            //     } else {
            //         goBack = true;
            //         $location.path(appContext.path + '/home');
            //         return;
            //     }
            // }

            $scope.getTotalPrice = function() {
                var totalPrice = cartService.getTotalPrice($rootScope.globalData.loginedCustomer._id);
                
                if (totalPrice <= 0) {
                    payTheBillBtn.addClass("disabled");
                } else {
                    payTheBillBtn.removeClass("disabled");
                }
                return totalPrice;
            }
        }
    });


    /** 
     * initilaize
     */
    console.log("Merchant ID: " + $stateParams.mId);

    var mask = $("#o2oc-restaurant-panel .mask");
    var fixedBtns = $('#o2oc-restaurant-panel .fixed-btns');
    var cartMenu = $("#o2oc-restaurant-panel .cart-menu");
    var payTheBillBtn = $("#o2oc-restaurant-panel .pay-the-bill-btn");

    var isAnimating = false;


    /** 
     * merchant management
     */
    $scope.merchant = {};
    merchantService.getMerchantById($stateParams.mId).then(
        function(response) {
            if (response.data.result) {
                $scope.merchant = response.data.data;
                if (!goBack) {
                    window.sessionStorage.setItem('currentMerchant', JSON.stringify($scope.merchant));
                }
            }
        },
        function(err) {
            console.log(err.data);
        }
    );


    /** 
     * dish management
     */
    $scope.dishes = [];
    dishService.getDishListByMerchantId($stateParams.mId).then(
        function(response) {
            if (response.data.result) {
                $scope.dishes = response.data.data;
            }
        },
        function(err) {
            console.log(err.data);
        }
    );


    /** 
     * dish searching
     */
    $rootScope.$on('doDishSearch', function(event, args) {
        // console.log(args);
        dishService.searchDishes($stateParams.mId, args).then(
            function(response) {
                if (response.data.result) {
                    $scope.dishes = response.data.data;
                }
            },
            function(err) {
                console.log(err.data);
            }
        );
    });


    /** 
     * comment management
     */
    merchantService.getCommentListByMerchantId($stateParams.mId).then(
        function(response) {
            console.log(response.data);
            if (response.data.result) {
                $scope.merchantComments = response.data.data;
            }
        },
        function(err) {
            console.log(err.data);
        }
    );


    /** 
     * cart management
     */
    $scope.showCartMenu = function() {
        cartMenu.animate({ right: 0 }, 200);
        mask.css({ display: "block" });
        mask.animate({ opacity: 0.5 }, 200);
    }

    $scope.hideCartMenu = function() {
        cartMenu.animate({ right: "-400px" }, 200);
        mask.animate({ opacity: 0 }, 200, function() {
            mask.css({ display: "none" });
        });
    }

    $scope.increaseCartItem = function(e, cartItemId) {
        if (!$scope.cart) {
            return;
        }
        var plusBtn = e.currentTarget;
        var minusBtn = $(plusBtn).prev().prev();
        $scope.cart.filter(function(cartItem) {
            return cartItem._id == cartItemId
        })[0].num++;
        cartService.setCart($rootScope.globalData.loginedCustomer._id, $scope.cart);
        minusBtn.removeClass('cursor-disabled');
    }

    $scope.decreaseCartItem = function(e, cartItemId) {
        if (!$scope.cart) {
            return;
        }
        var minusBtn = e.currentTarget;
        var _cartItem = $scope.cart.filter(function(cartItem) {
            return cartItem._id == cartItemId
        })[0];

        if (_cartItem.num > 0) {
            _cartItem.num--;
            cartService.setCart($rootScope.globalData.loginedCustomer._id, $scope.cart);
            if (_cartItem.num <= 0) {
                $(minusBtn).addClass('cursor-disabled');
            }
        }
    }

    $scope.removeCartItem = function(cartItemId) {
        if (!$scope.cart) {
            return;
        }
        var indexToRemove = 0;
        $scope.cart.forEach(function(item, index) {
            if (item._id == cartItemId) {
                indexToRemove = index;
            }
        });
        $scope.cart.splice(indexToRemove, 1);
        cartService.setCart($rootScope.globalData.loginedCustomer._id, $scope.cart);
    }

    $scope.addItemToCart = function($event, dishItem) {
        if (isAnimating) {
            return;
        }

        if (!$rootScope.globalData.loginedCustomer) {
            $location.path(appContext.path + '/login');
            return;
        }

        if (!$scope.cart) {
            return;
        }

        var img = $($event.currentTarget).prev();
        beginAddToCartAnimation(img, fixedBtns, function() {
            // send ajax req

            var cartItem = $scope.cart.filter(function(item) {
                return item._id == dishItem._id;
            })[0];
            if (cartItem) {
                cartItem.num++;
            } else {
                // cart item model definition
                $scope.cart.push({
                    _id: dishItem._id,
                    dishName: dishItem.name,
                    unitPrice: dishItem.price,
                    num: 1,
                    img: dishItem.img
                });
            }

            cartService.setCart($rootScope.globalData.loginedCustomer._id, $scope.cart);
        });
    }

    function beginAddToCartAnimation(fromElement, toElement, callback) {
        isAnimating = true;
        var fromOffset = fromElement.offset();
        
        var fromClone = fromElement.clone();
        fromClone.css({
            position: 'fixed',
            width: fromElement.css('width'),
            height: fromElement.css('height'),
            top: fromOffset.top - $(window).scrollTop(),
            left: fromOffset.left - $(window).scrollLeft()
        });
        $('#o2oc-restaurant-panel').append(fromClone);

        fromClone.animate({
            opacity: 0.5,
            width: toElement.width(),
            height: toElement.height(),
            top: toElement.css('top'),
            left: toElement.css('left'),
        }, {
            duration: 1000,
            specialEasing: {
                top: 'easeInQuad',
                left: 'easeOutQuad'
            },
            complete: function() {
                fromClone.remove();
                toElement.effect('shake', {
                    direction: 'up',
                    distance: 10
                });
                callback();
                isAnimating = false;
            }
        });
    }
    
    $scope.hideModal = function(modalName) {
        $('#o2oc-restaurant-panel .' + modalName + '-modal').modal('hide');
    }

}

module.exports = restaurantController;